<?PHP

require_once WACT_ROOT . 'db/db.inc.php';
require_once WACT_ROOT .'util/arraydataset.inc.php';
require_once APP_ROOT.'model/common/site.php';

class CategoryFilter{
	var $selected_id;
	function CategoryFilter($id){
		$this->selected_id=$id;
	}

	function doFilter(&$vars){
		error_log("[filter]".$this->selected_id);
    	if($vars['linked_category_id']!=$this->selected_id) {
    		$vars['selected']=null;
    	}
	}
}

class CategoryPermissionFilter {

	function CategoryPermissionFilter() {
	}

	function doFilter(&$vars){

        $premium = $vars['premium'];
        if ($premium)  $vars['premium_show']=1;
        else $vars['premium_show']=0;
	}
}

class CategoriesModel{
	var $leftMenuCount=0;

	function CategoriesModel(){
	}

	function AreCategoriesLinked($category1_id, $category2_id) {

			$sql = " select * from sport_categories_relations where category_id = ".DBC::makeLiteral($category1_id).
			" and linked_category_id = ".DBC::makeLiteral($category2_id);

			error_log("[TRABLA]$sql");
			$rs =& DBC::NewRecordSet($sql);
			//print_r($rs);
			$rs->reset();
			if (!$rs->next()) { //print 'Not Linked!';
				return false;
			}
			else {
				//print 'Linked!';
				return true;
			}
	}


	//type=1 - Sport categories; type=2 - Sport Community;
	function &getLeftMenu() {
	    $site_id = Site::getSiteID();
		$query="select category_id,name  from sport_categories where type=2 and showTopMenu =1 and site_id = ".DBC::makeLiteral($site_id);
		$query.=" order by sortOrder";
		$result=DBC::NewRecordSet($query);
		$result->reset();
		$i=1;
		$menuar=array();
       	while($result->next()){
       			$subtable=array();
      			$dataArray=$result->getPropertyList();
      			foreach($dataArray as $index=>$property){
					$subtable=array_merge($subtable,array($property=>$result->get($property)));
      			}
      			$subtable=array_merge($subtable,array('number'=>$i));
      			$i++;
				$menuar=array_merge($menuar,array($subtable));
      	}
    	$this->leftMenuCount=$i;
      	$menuList=new ArrayDataSet($menuar);
		return $menuList;
	}

	function &getRightMenu() {
	    $site_id = Site::getSiteID();
		$query="select category_id,name  from sport_categories where type=1 and site_id = ".DBC::makeLiteral($site_id);
		$query.=" order by sortOrder";
		$result = DBC::NewRecordSet($query);
		$result->reset();
		$i=$this->leftMenuCount;
		$menuar=array();
       	while($result->next()){
       			$subtable=array();
      			$dataArray=$result->getPropertyList();
      			foreach($dataArray as $index=>$property){
					$subtable=array_merge($subtable,array($property=>$result->get($property)));
      			}
      			$subtable=array_merge($subtable,array('number'=>$i));
      			$i++;
				$menuar=array_merge($menuar,array($subtable));
      	}

      	$menuList=new ArrayDataSet($menuar);
		return $menuList;
	}

	function &getTopDownMenuList() {
		$leftmenu=&CategoriesModel::getLeftMenu();
		$rightmenu=&CategoriesModel::getRightMenu();
		$menuar=array();
		while($leftmenu->next()){
       			$subtable=array();
      			$dataArray=$leftmenu->getPropertyList();
      			foreach($dataArray as $index=>$property){
					$subtable=array_merge($subtable,array($property=>$leftmenu->get($property)));
      			}
      			$subtable=array_merge($subtable,array('submenu'=>CategoriesModel::getSubmenuList($leftmenu->get('category_id'))));
				$menuar=array_merge($menuar,array($subtable));
      	}
		while($rightmenu->next()){
       			$subtable=array();
      			$dataArray=$rightmenu->getPropertyList();
      			foreach($dataArray as $index=>$property){
					$subtable=array_merge($subtable,array($property=>$rightmenu->get($property)));
      			}
      			$subtable=array_merge($subtable,array('submenu'=>CategoriesModel::getSubmenuList($rightmenu->get('category_id'))));
				$menuar=array_merge($menuar,array($subtable));
      	}
		$menuList=new ArrayDataSet($menuar);
		return $menuList;

	}

	function getSubmenuList($id) {
		$site_id = Site::getSiteID();
		$query="select a.type, b.category_id ,b.linked_category_id ,a.name as \"name\" ";
		$query.=" from sport_categories a, sport_categories_relations b ";
		$query.=" where b.linked_category_id=a.category_id and  b.category_id=$id";
        $query.=" and a.site_id = ".DBC::makeLiteral($site_id);
        $query.=" order by a.sortOrder";
		$result=DBC::NewRecordSet($query);

		$result->reset();
		$script='';
		while($result->next()){
			$session_url='';
			if(defined('SID')&&(!isset($_COOKIE[session_name()])))
    	 		$session_url.='&'.SID;
			if($result->get('type')==2){
				$categories='sport='.$result->get('category_id').'&community='.$result->get('linked_category_id');
			}else
				$categories='sport='.$result->get('linked_category_id').'&community='.$result->get('category_id');
			$script.="[".$result->get('name').",articles/category.htm?".$categories.$session_url."]";
		}
		return $script;

	}

    //type=1 - Sport categories; type=2 - Sport Community;
    //get the array of normal/premium sport categories of type 1
	function &getSportCategories($normal=true, $premium=false, $none=false ) {
	    $site_id = Site::getSiteID();
		$query="select category_id,name  from sport_categories where type=1 ";
        if ($normal) $query .= " and normal=1 ";
        if ($premium) $query .= " and premium=1 ";
        $query .= " and site_id = ".DBC::makeLiteral($site_id);
        $query.=" order by sortOrder";
		$result =& DBC::NewRecordSet($query);
		$result->reset();
		//$i=1;
        $categories=array();

        if ($none) $categories['0']='(ALL)';

        while($result->next()) {
        		$id =  $result->get('category_id');
        		$name = $result->get('name');
        		if ($premium) $name = 'Premium '. $name;
        		//$categories=array_merge($categories,array($id=>$name));
                $categories[$id]= $name;
        }
        return $categories;
	}

    // checks category permissions
    function &getSportCategoriesForAuthor($user_id, $none=false ) {
        $site_id = Site::getSiteID();
		$query = "select C.category_id, C.name
        from sport_categories C
    	inner join sport_category_permissions CP
    	on C.category_id = CP.category_id
    	where type=1 and
    	CP.user_id = ".DBC::makeLiteral($user_id)."
    	and C.site_id = ".DBC::makeLiteral($site_id);
    	$query.=" order by C.sortOrder";

      //  if ($normal) $query .= " and C.normal=1 ";
      //  if ($premium) $query .= " and C.premium=1 ";
		$result =& DBC::NewRecordSet($query);
		$result->reset();
		//$i=1;
        $categories=array();

        if ($none) $categories['0']='(ALL)';

        while($result->next()) {
        		$id =  $result->get('category_id');
        		$name = $result->get('name');
        	//	if ($premium) $name = 'Premium '. $name;
        		//$categories=array_merge($categories,array($id=>$name));
                $categories[$id]= $name;
        }
        return $categories;
	}

    function &getSportCategoriesWithPermissions($user_id) {
        $site_id = Site::getSiteID();
    	$query = "select C.*, CP.*  from sport_categories C
    	inner join sport_category_permissions CP
    	on C.category_id = CP.category_id
    	where type=1 and
    	CP.user_id = ".DBC::makeLiteral($user_id)."
    	and C.site_id = ".DBC::makeLiteral($site_id)."
    	order by C.sortOrder, C.`name` ";
    	$result =& DBC::NewRecordSet($query, new CategoryPermissionFilter());
    	return $result;
    }

    //type=1 - Sport categories; type=2 - Sport Community;
    //get the array of normal/premium community categories of type 2
	function &getCommunityCategories($normal=true, $premium=false, $none=false ) {
		$site_id = Site::getSiteID();
		$query = "select category_id,name  from sport_categories where type=2  ";
        if ($normal) $query .= " and normal=1 ";
        if ($premium) $query .= " and premium=1 ";
        $query .= " and site_id =  ".DBC::makeLiteral($site_id);
        $query.=" order by sortOrder";
		$result =& DBC::NewRecordSet($query);
		$result->reset();
		//$i=1;
        $categories=array();

        if ($none) $categories['0']='(ALL)';

        while($result->next()) {
        		$id =  $result->get('category_id');
        		$name = $result->get('name');
        		if ($premium) $name = 'Premium '. $name;
        		//$categories=array_merge($categories,array($id=>$name));
                $categories[$id]= $name;
        }
        return $categories;
	}

    function &getAllCategories() {
        $site_id = Site::getSiteID();
    	$query = "select *  from sport_categories where site_id = ".DBC::makeLiteral($site_id)." order by `type`, sortOrder, `name`";
    	$result =& DBC::NewRecordSet($query);
    	return $result;
    }

    // get human readable category type
    function getHRType($type) {
    	if ($type==1) return 'Sport category';
    	elseif ($type==2) return 'Sports community';
    	elseif ($type==3) return 'Other';
    	else return 'Other';
    }

     function &getRecord($id) {
        return DBC::FindRecord("SELECT * FROM sport_categories C
        WHERE C.category_id=". DBC::makeLiteral($id));
    }

    function delete($id) {
        DBC::execute("DELETE FROM sport_categories WHERE category_id=". DBC::makeLiteral($id));
        DBC::execute("DELETE FROM sport_categories_relations WHERE category_id=". DBC::makeLiteral($id));
        DBC::execute("DELETE FROM sport_categories_relations WHERE linked_category_id=". DBC::makeLiteral($id));
    }

    function insertCategory(&$data) {
    	$site_id = Site::getSiteID();
    	$data->set('site_id',$site_id);
    	$data->set('showTopMenu',1);
        $Record =& DBC::NewRecord($data);
        return $Record->insertId('sport_categories',
            array('sortOrder', 'name','normal', 'premium', 'type','site_id','showTopMenu'), 'category_id');
    }

    function updateCategory($id, &$data) {
        $site_id = Site::getSiteID();
    	$data->set('site_id',$site_id);
        $Record =& DBC::NewRecord($data);
        $Record->update('sport_categories',
            array('sortOrder','name','normal', 'premium', 'type','site_id'),
            "category_id = ". DBC::makeLiteral($id));
    }

    // saves linked categories
    // $data - input array with rows
    function saveLinkedcategories(&$data, $category_id) {
    		 //$site_id = Site::getSiteID();
             $ds =& new DataSpace();
             DBC::execute("DELETE FROM sport_categories_relations WHERE category_id=". DBC::makeLiteral($category_id));

    		 foreach($data as $cat_id=>$row) {
    		 	//print_r($row);
                $ds->import($row);
                $Record =& DBC::NewRecord($ds);
       			$Record->insert('sport_categories_relations',
            	array('category_id', 'linked_category_id'));
    		 }
    }

    // loads linked categories
    // input: category_id
    // output: array $linked_categories
     function &loadLinkedcategories($category_id) {
       	$rs =& DBC::NewRecordSet('SELECT * FROM sport_categories_relations where category_id='. DBC::makeLiteral($category_id));
       	$rs->reset();
       	$linked_categories = array();

       	while($rs->next()) {
       	    $category_id = $rs->get('category_id');
            $linked_category_id = $rs->get('linked_category_id');

            // populate array
            $linked_categories[] = $linked_category_id;
       	}
       	return $linked_categories;
     }

     function &getLinkedCategoriesList($category_id,$com_id) {
            $site_id = Site::getSiteID();
     		return DBC::NewRecordSet("SELECT CR.*, C.name, \"selected\"
     		FROM sport_categories_relations CR
     		inner join sport_categories C
     		on CR.linked_category_id = C.category_id
     		where C.showTopMenu=1 and CR.category_id=". DBC::makeLiteral($category_id)." and C.site_id = ".DBC::makeLiteral($site_id).
     		" order by C.sortOrder "  , new CategoryFilter($com_id));

     }

     // returns the linked categories as comma separated string
     function getLinkedCategories($category_id) {
        $site_id = Site::getSiteID();
     	$rs =& DBC::NewRecordSet('SELECT CR.*, C.name
     	FROM sport_categories_relations CR
     	inner join sport_categories C
     	on CR.linked_category_id = C.category_id
     	where CR.category_id='. DBC::makeLiteral($category_id).' and C.site_id = '.DBC::makeLiteral($site_id)
     	." order by C.sortOrder ");
       	$rs->reset();
        $linked_categories = '';
        $i = 0;
        while($rs->next()) {
       	    $category_id = $rs->get('category_id');
            $linked_category_id = $rs->get('linked_category_id');
            $linked_category_name = $rs->get('name');

            // populate array
            if ($i==0) $linked_categories .= $linked_category_name;
            else $linked_categories .= ", ".$linked_category_name;
            $i++;
       	}
       	return $linked_categories;

     }


}

?>
